package com.rayson.oneapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rayson.oneapi.exception.BusinessException;
import com.rayson.oneapi.mapper.InterfaceInfoMapper;
import com.rayson.oneapi.model.entity.InterfaceInfo;
import com.rayson.oneapi.model.enums.ErrorCode;
import com.rayson.oneapi.model.enums.InterfaceInfoStatusEnum;
import com.rayson.oneapi.model.req.IdRequest;
import com.rayson.oneapi.model.req.interfaceinfo.InterfaceInfoAddReq;
import com.rayson.oneapi.model.req.interfaceinfo.InterfaceInfoListReq;
import com.rayson.oneapi.model.req.interfaceinfo.InterfaceInfoUpdateReq;
import com.rayson.oneapi.service.InterfaceInfoService;
import com.rayson.oneapi.service.UserService;
import com.rayson.oneapi.util.PageUtil;
import com.rayson.oneapi.util.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author wulei
 * @description 针对表【interface_info(接口信息表)】的数据库操作Service实现
 * @createDate 2024-08-21 20:02:22
 */
@Slf4j
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
        implements InterfaceInfoService {

    @Resource
    private UserService userService;


    @Override
    public Page<InterfaceInfo> queryPage(InterfaceInfoListReq listReq) {
        LambdaQueryWrapper<InterfaceInfo> queryWrapper = lambdaQuery().getWrapper()
                .like(StringUtils.hasText(listReq.getName()), InterfaceInfo::getName, listReq.getName())
                .like(StringUtils.hasText(listReq.getDesc()), InterfaceInfo::getDesc, listReq.getDesc())
                .like(StringUtils.hasText(listReq.getUrl()), InterfaceInfo::getUrl, listReq.getUrl())
                .eq(Objects.nonNull(listReq.getHttpMethod()), InterfaceInfo::getHttpMethod, listReq.getHttpMethod())
                .eq(Objects.nonNull(listReq.getStatus()), InterfaceInfo::getStatus, listReq.getStatus());

        return this.page(PageUtil.getPage(listReq), queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(InterfaceInfoAddReq addReq) {
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(addReq, interfaceInfo);
        interfaceInfo.setCreateBy(userService.getLoginUser(ServletUtil.getRequest()).getId());
        this.save(interfaceInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateInterfaceInfo(InterfaceInfoUpdateReq updateReq) {
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(updateReq, interfaceInfo);
        this.updateById(interfaceInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteInterfaceInfo(String id) {
        boolean delFlag = this.removeById(id);
        log.info("删除接口【{}】：{}", id, delFlag);
    }

    @Override
    public void onlineInterfaceInfo(IdRequest idRequest) {
        String id = idRequest.getId();
        // 1.接口是否存在？
        InterfaceInfo interfaceInfo = this.getById(id);
        if (Objects.isNull(interfaceInfo)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 2.是否已经上线？
        if (InterfaceInfoStatusEnum.ONLINE.getValue() == interfaceInfo.getStatus()) {
            log.info("接口【{}】已经上线，无需重复上线", id);
            return;
        }
        // TODO 3.接口是否可以正常调用

        // 4.修改状态为上线
        LambdaUpdateWrapper<InterfaceInfo> updateWrapper = lambdaUpdate().getWrapper()
                .eq(InterfaceInfo::getId, id)
                .set(InterfaceInfo::getStatus, InterfaceInfoStatusEnum.ONLINE.getValue());
        boolean updateFlag = this.update(updateWrapper);
        log.info("上线接口【{}】成功：{}", id, updateFlag);
    }

    @Override
    public void offlineInterfaceInfo(IdRequest idRequest) {
        String id = idRequest.getId();
        // 1.接口是否存在？
        InterfaceInfo interfaceInfo = this.getById(id);
        if (Objects.isNull(interfaceInfo)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // TODO 接口是否是正常上线状态
        if (InterfaceInfoStatusEnum.ONLINE.getValue() != interfaceInfo.getStatus()) {
            throw new BusinessException("接口状态异常，不能下线");
        }
        // 2.是否已经下线？
        if (InterfaceInfoStatusEnum.OFFLINE.getValue() == interfaceInfo.getStatus()) {
            log.info("接口【{}】已经下线，无需重复下线", id);
            return;
        }

        // 3.修改状态为下线
        LambdaUpdateWrapper<InterfaceInfo> updateChainWrapper =
                lambdaUpdate().getWrapper().eq(InterfaceInfo::getId, id)
                        .set(InterfaceInfo::getStatus, InterfaceInfoStatusEnum.OFFLINE.getValue());
        boolean updateFlag = this.update(updateChainWrapper);
        log.info("下线接口【{}】成功：{}", id, updateFlag);
    }
}




